package com.hw.weathershow.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static io.netty.handler.codec.http.HttpMethod.OPTIONS;

/**
 * The type Customed web mvc configurer.
 */
@Configuration
//该注解表示我们全面接管webMvcConfigurer的配置管理，取消了springboot的默认配置。如果删去，那么long丢失问题无法解决
@EnableWebMvc
public class CustomedWebMvcConfigurer implements WebMvcConfigurer {

    @Override//处理跨域请求
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .exposedHeaders("Content-Disposition","state")
        ;
//        是否允许携带cookie，若允许，则allow-origin 不能为"*"
//                .allowCredentials(true);

//        // 如果是OPTIONS则结束请求
//        if (OPTIONS.equals(((HttpServletRequest) request).getMethod())) {
//            response.getWriter().println("ok");
//            return;
//        }
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }

    //    配置信息传递时的格式转换
//    解决Long从后转前的精度丢失问题
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper objectMapper = new ObjectMapper();
        /**
         * 序列换成json时,将所有的long变成string
         * 因为js中得数字类型不能包含所有的java long值
         */
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }
}
